package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApLoginUserService;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;

@Service
public class ApLoginUserServiceImpl implements ApLoginUserService {
    @Autowired
    private ApUserMapper apUserMapper;

    @Override
    public ResponseResult login(LoginDto dto) {
        //判断数据是否合法
        if (dto == null) {
            CustomException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        String phone = dto.getPhone();
        String password = dto.getPassword();
        Integer equipmentId = dto.getEquipmentId();
        if (StringUtils.isNotBlank(phone)) {
            //判断数据库中是否存在该数据
            LambdaQueryWrapper<ApUser> wrapper = Wrappers.lambdaQuery();
            wrapper.eq(ApUser::getPhone, phone);
            ApUser apUser = apUserMapper.selectOne(wrapper);
            if (apUser == null) {
                CustomException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "账号输入错误，请检查后重试！！！");
            }
            //处理用户输入的密码
            password = password + apUser.getSalt();
            String pwd = DigestUtils.md5DigestAsHex(password.getBytes());
            if (!pwd.equals(apUser.getPassword())) {
                CustomException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR, "密码输入错误，请检查后重试！！");
            }
            //查看用户状态
            if (apUser.getStatus()==1) {
                CustomException.cust(AppHttpCodeEnum.LOGIN_STATUS_ERROR, "当前账户为锁定状态");
            }
            apUser.setPassword("");
            apUser.setSalt("");
            //登录成功，则颁发token
            String token = AppJwtUtil.getToken(Long.valueOf(apUser.getId()));
            HashMap map = new HashMap<>();
            map.put("user", apUser);
            map.put("token", token);
            return ResponseResult.okResult(map);
        }
        //如果用户选择暂不登录，则只需要将用户的设备id写入token即可
        ApUser apUser = new ApUser();
        apUser.setId(0);
        apUser.setPassword("");
        apUser.setSalt("");
        String token = AppJwtUtil.getToken(0l);
        HashMap map = new HashMap<>();
        map.put("token", token);
        map.put("user", apUser);
        return ResponseResult.okResult(map);
    }
}
